/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.velocityme.session;

import com.velocityme.entity.ChangeDelta;
import com.velocityme.entity.Group;
import com.velocityme.entity.User;
import com.velocityme.enums.ChangeDeltaItemType;
import com.velocityme.enums.ChangeDeltaType;
import com.velocityme.enums.Permission;
import java.util.ArrayList;
import java.util.Collection;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

/**
 *
 * @author rcrida
 */
@Stateless
public class GroupBean implements GroupLocal {

    @PersistenceContext
    private EntityManager em;

    @EJB
    private NodeLocal nodeBean;

    public Collection<Group> findAllGroups(KeyLocal key) {
        key.validateKey();
        return em.createNamedQuery("findAllGroups").getResultList();
    }

    public Group findGroup(KeyLocal key, Long groupId) {
        Group group = em.find(Group.class, groupId);
        key.assertHasPermission(group, Permission.NODE_VIEW);
        return group;
    }

    public Group createGroup(KeyLocal key, Group group) {
        key.assertHasPermission(group.getParentNode(), Permission.GROUP_CREATE);
        ChangeDelta changeDelta = group.addChangeDelta(ChangeDeltaType.CREATE, key.getUser());
        nodeBean.logCreate(group, changeDelta);
        for (User user: group.getUsers()) {
            changeDelta.addItem(ChangeDeltaItemType.ADD_USER, user.getPersonUserName());
            em.merge(user);
        }
        em.persist(group);
        em.persist(changeDelta);
        return group;
    }

    public void editGroup(KeyLocal key, Group group) {
        Group current = em.find(Group.class, group.getId());
        key.assertHasPermission(group, Permission.GROUP_EDIT);
        ChangeDelta changeDelta = group.addChangeDelta(ChangeDeltaType.EDIT, key.getUser());
        nodeBean.logEdit(group, current, changeDelta);
        // check users
        Collection<User> usersRemoved = new ArrayList<User>(current.getUsers());
        usersRemoved.removeAll(group.getUsers());
        Collection<User> usersAdded = new ArrayList<User>(group.getUsers());
        usersAdded.removeAll(current.getUsers());
        for (User user: usersRemoved) {
            changeDelta.addItem(ChangeDeltaItemType.REMOVE_USER, user.getPersonUserName());
            em.merge(user);
        }
        for (User user: usersAdded) {
            changeDelta.addItem(ChangeDeltaItemType.ADD_USER, user.getPersonUserName());
            em.merge(user);
        }
        em.persist(changeDelta);
        em.merge(group);
    }
 
}
